import { divideByHundred } from '../../utils/util.js'
import { HTTP } from '../../utils/http.js'
import api from '../../utils/api.js'
import { config } from '../../utils/config'
import common from '../../utils/common'

const http = new HTTP()
const app = getApp();
Page({

    data: {
        // 此页面 页面内容距最顶部的距离
        height: app.globalData.height * 2 + 20,
        hidden: [false, false, false, false, false], //伸缩展开
        animationArr: [], //动画
        scrollDown: 0,
        height: app.globalData.height * 2 + 20,
        shopList: [], //筛选出来的店铺
        disableShopList: [],
        totalPrice: 0.00, //总价
        selectedMenus: [], //选择的菜谱
        singleShopMenus: [], //当个店铺可卖菜谱
        distance: [], //距离
        priceTotal: [], //预估总价
        errcode: '',
        imgUrl: config.imgUrl,
        receivingIndex: 0,
        noStore: false,
        // receivingType: ['自提', '配送', '自选'],
        receivingType: ['自提'],
        payBtn: true,
        timerShow: false,
        currentSelectTime: '',
        currentTimeIndex: 0,
        list: [
            { url: "https://images.weigeee.com/20190902/d807f19c6423d192b8901b8bf44b0fd8.jpg", name: "蔡夫人" },
            { url: "https://images.weigeee.com/20190902/9bb905d4038f05eab2057df991db4d38.png", name: "谊品生鲜" },
            { url: "https://images.weigeee.com/20190902/afca7e69786139aaca317dcc8b7b3010.png", name: "厨鲜生" },
        ],
        objectMultiShow: [],
        objectMultiArray: [],
        multiArray: [],
        multiIndex: [],
        multiIndex: [0, 0], //默认显示的内容
        month: common.date.month,
        // deleteDialog: {
        //     show: false,
        //     showCancel: true,
        //     showConfirm: true,
        //     toggle: function () {
        //         this.show = !this.show;
        //         return this;
        //     },
        // }
    },

    // 菜篮操作
    add(e) {
        let self = this;
        const tIndex = e.currentTarget.dataset.tindex; //点击菜谱是最高tindex
        const classes_id = e.currentTarget.dataset.classes_id; // 三级分类，土豆，肋排id
        const product_id = e.currentTarget.dataset.product_id; //单一商品的 id

        // 获取商品数据
        let list = this.data.myAllItem[tIndex];
        // 给 当前 子项增加商品数量: num 属性
        list.forEach((ele) => {
            if (ele.classes_id == classes_id) { //验证外层分类id 是否等于 单品分类id  129
                if (ele.son) { //若没有三级单品，则跳过，不报错
                    ele.son.forEach((ele) => {
                        if (ele.product_id == product_id) {
                            self.judgeproductStock(ele);
                        } else {
                            ele.mark = false
                        }
                    })
                }
            }
        });

        let myAllItem = 'myAllItem' + '[' + tIndex + ']'
        this.setData({
            [myAllItem]: list
        });
        this.totalPrice(e); //计算总价
        this.checkMenus(e); //确定选择的菜单
    },
    // 获取时间
    selectTimes() {
        http.request({
            url: api.orderGetTime,
            method: "GET",
            success: (res) => {
                if (res.code == 200) {
                    let timeData = res.data;

                    let timeObj = [];
                    let timeList = [];
                    let cnName = ''
                    let dayId = 0;
                    for (let key of Object.keys(timeData)) {
                        if (key == "today") {
                            cnName = '今天';
                            dayId = 1
                        } else if (key == "tomorrow") {
                            cnName = '明天'
                            dayId = 2
                        }
                        let fullName = cnName + ' ' + timeData[key].week + ' '
                        timeObj.push({ name: fullName, cnName: cnName, id: key, dayId: dayId })

                        let time = timeData[key].time
                        time.forEach(item => {
                            timeList.push({ name: item, parentId: key })
                        })
                    }
                    let data = {
                        timeObj: timeObj,
                        objectMultiShow: this.data.objectMultiShow,
                        objectMultiArray: this.data.objectMultiArray,
                        multiArray: this.data.multiArray,
                        multiIndex: this.data.multiIndex,
                    }
                    data.objectMultiArray[0] = timeObj;
                    data.objectMultiArray[1] = timeList;
                    this.setData({
                        timeObj
                    })
                    data.objectMultiShow = data.objectMultiArray.map((item, index) => {
                        if (index > 0) {
                            item = item.filter(i => i.parentId === data.objectMultiArray[index - 1][0].id)
                        }
                        return item
                    })
                    data.multiArray = data.objectMultiShow.map(item => {
                        item = item.map(i => i.name)
                        return item
                    })
                    // 数据更新
                    this.setData(data);
                    let HandValue = [0, 0]
                    let selectname = data.objectMultiArray[0][HandValue[0]].cnName
                    let selectdayId = data.objectMultiArray[0][HandValue[0]].dayId;
                    let selecthours = data.objectMultiArray[1][HandValue[1]].name;
                    this.setData({
                        currentSelectTime: {
                            selectname,
                            selectdayId,
                            selecthours
                        }
                    })

                }
            },
            fail: (res) => {
                console.log('error', res)
            }
        })
    },

    //进入店铺详情
    enterDetail(e) {
        let type = this.data.type;
        let shopList = this.data.shopList;
        wx.setStorageSync('shopList', shopList)
        if (type == 1) { //从菜谱进入，去选择食材页面
            let shopId = e.currentTarget.dataset.id //店铺id
            let index = e.currentTarget.dataset.index //当前店铺 在数组的索引值
            wx.navigateTo({
                url: `/pages/recommend/recommend?shopId=${shopId}&index=${index}`,
            })
        } else if (type == 2) { //从支付成功再次进入-筛选店铺
            let shopId = e.currentTarget.dataset.id
            let index = e.currentTarget.dataset.index
            wx.navigateTo({
                url: `/pages/recommend/recommend?shopId=${shopId}&index=${index}`,
            })
        }

    },
    // 去店铺 评***价页面
    enterShopEvaluationList(e) {
        let shopId = e.currentTarget.dataset.shopid
        wx.setStorageSync('evalutionListShopId', shopId)
        wx.navigateTo({
            url: `/pages/userEvaluationList/userEvaluationList?shopId=${shopId}`,
        })
    },
    // 去推荐码页面
    goToRecommendCode() {
        wx.redirectTo({
            url: '/pages/member-friend/member-friend'
        })
    },
    deleteMenu(e) {
        const Jingwei = wx.getStorageSync('address');
        let index = e.currentTarget.dataset.index;
        let selectedMenusStorage = wx.getStorageSync('select-menus');
        let selectedMenus = this.data.selectedMenus;
        if (selectedMenus.length >= 1) {
            selectedMenusStorage.splice(index, 1)
            selectedMenus.splice(index, 1)
            wx.setStorageSync('select-menus', selectedMenusStorage)
            this.setData({
                selectedMenus
            })
            this.getMerchantShop(Jingwei, selectedMenus)
            if (selectedMenus.length == 0) {
                // wx.showToast({
                //   title: '您需要保留一个菜谱',
                //   icon: "none",
                //   duration: 1500
                // })
                wx.switchTab({
                    url: '/pages/index/index',
                })
            }
        }
    },

    getMerchantShop(Jingwei, selectedMenus) {
        let shopId = []; // 店铺id
        let menusId = []; //菜谱id
        selectedMenus.forEach((ele, i) => {
            menusId.push(ele.id)
        })
        this.choiceMerchantShop(Jingwei.latitude, Jingwei.longitude, shopId, menusId);
    },

    onLoad: function (options) {
        //每次进入页面重新加载经纬度
        const Jingwei = wx.getStorageSync('address')

        // 先查询缓存 是否存在地址   
        if (Jingwei.id && Jingwei.city_id) {
            this.setData({
                address_id: Jingwei.id,
                address: Jingwei
            })
        }

        let selectedMenus = wx.getStorageSync('select-menus')
        this.setData({
            selectedMenus,
            type: options.type
        })

        var products = wx.getStorageSync('payList');
        this.setData({
            payList: products
        })

        this.getShopList(Jingwei.latitude, Jingwei.longitude, products);
        this.selectTimes();
    },

    /*shopList 根据菜谱请求店铺接口*/
    getShopList(lat, lng, products) {
        let that = this;
        http.request({
            url: api.shopList,
            data: {
                lng: lng,
                lat: lat,
                products
            },
            success: (res) => {
                if (res.error_code == 400000 && res.msg) {
                    that.setData({
                        noStore: true
                    })
                    return;
                } else if (res.code == 200 && res.data) {
                    var payList = wx.getStorageSync('payList');
                    var totalPrice;
                    const data = res.data;
                    var isdisplay = 0;
                    if (data) {
                        data.forEach((item, index) => {
                            totalPrice = 0;
                            Object.assign(item, { 'open': false, 'receiving_method': 0 })
                            if (item.product && item.product.length > 0) {
                                item.product.forEach(key => {
                                    for (const i of payList) {
                                        if (key.id == i.product_id) {
                                            totalPrice += key.price * i.num;
                                            Object.assign(key, { 'buyNumber': i.num })
                                        }
                                    }
                                })
                                data.totalPrice = totalPrice;
                            } else {
                                isdisplay += 1
                            }
                            Object.assign(item, { 'totalPrice': totalPrice });

                            // 匹配出缺少的蔬菜
                            let currentShop = item.product
                            var result = '';
                            var resultArr = [];
                            for (var k = 0; k < payList.length; k++) {
                                var obj = payList[k];
                                var num = obj.product_id;
                                var isExist = false;
                                for (var j = 0; j < currentShop.length; j++) {
                                    var aj = currentShop[j];
                                    var n = aj.id;
                                    if (n == num) {
                                        isExist = true;
                                        break;
                                    }
                                }
                                if (!isExist) {
                                    result += obj.name + ',';
                                    resultArr.push(obj.name)
                                }
                            }
                            item.less = result.substr(0, result.length - 1);
                            item.lessCount = resultArr.length
                        })

                        if (data.length === isdisplay) {
                            that.setData({
                                noStore: true
                            })
                        }
                        that.setData({
                            shopList: data
                        })


                    }
                }
                if (res.error_code == 400001) {
                    that.setData({
                        shopList: [],
                        errcode: res.msg
                    })
                }

            }
        })
    },
    choseAddress(e) {

        wx.navigateTo({
            url: `/pages/addAddress/addAddress`
        })
    },
    // 点击商品右侧增加按钮
    NumberAdd: function (e) {
        var pid = e.currentTarget.dataset.pid;
        var sid = e.currentTarget.dataset.sid;
        var shopList = this.data.shopList;
        let payList = wx.getStorageSync('payList')
        //获取店铺内容

        shopList.forEach(item => {
            var totalPrice = 0
            if (item.id === pid) {
                for (let k of item.product) {
                    if (k.id == sid) {
                        k.buyNumber++
                    }
                    totalPrice += k.price * k.buyNumber;
                }
                item.totalPrice = totalPrice
            }

        })
        this.setData({
            shopList
        })
    },
    // 点击商品左侧减少按钮
    NumberLess: function (e) {
        var that = this
        var pid = e.currentTarget.dataset.pid;
        var sid = e.currentTarget.dataset.sid;
        var shopList = this.data.shopList;
        // let payList = wx.getStorageSync('payList') 
        //获取店铺内容
        shopList.forEach(item => {
            var totalPrice = 0;
            if (item.id == pid) {
                item.product.forEach((k, index) => {
                    if (k.id == sid) {
                        if (k.buyNumber == 1) {
                            wx.showModal({
                                title: '提示',
                                content: '要删除这个菜品吗？',
                                confirmColor: '#EA5D56',
                                success(res) {
                                    if (res.confirm) {
                                        // 删除商品操作
                                        item.product.splice(index, 1);
                                        k.buyNumber--;
                                        item.totalPrice -= k.price
                                        // wx.setStorageSync('payList',payList)
                                        that.setData({
                                            shopList
                                        })
                                    } else if (res.cancel) {
                                        return;
                                    }
                                }
                            })

                        } else {
                            k.buyNumber--
                        }
                    }
                    totalPrice += k.price * k.buyNumber;
                })
                item.totalPrice = totalPrice
            }
        })
        this.setData({
            shopList
        })
    },
    // 点击详情按钮
    ShowView(e) {
        var currentid = e.currentTarget.dataset.id;
        var shopList = this.data.shopList;
        shopList.forEach(item => {
            item.open = false;
            if (item.id === currentid && item.product.length > 0) {
                item.open = true;
            }
        })
        this.setData({
            shopList
        })
    },
    CloseView(e) {
        var currentid = e.currentTarget.dataset.id;
        var shopList = this.data.shopList;
        shopList.forEach(item => {
            if (item.id === currentid) {
                item.open = false
            }
        })
        this.setData({
            shopList
        })
    },
    // 去下单
    placeOrder(e) {
        if (!this.data.payBtn) {
            return false
        } else {
            this.setData({
                payBtn: false
            })
        }

        let that = this;
        var pid = e.currentTarget.dataset.pid;
        let products = [];
        let receiving_method;
        let shopList = that.data.shopList;
        let selectedMenus = this.data.selectedMenus;
        var cookbookids = [];
        // 菜谱
        if (selectedMenus) {
            selectedMenus.forEach(item => {
                cookbookids.push(item.cookId)
            })
        }

        shopList.forEach((item) => {
            if (item.id === pid) {
                receiving_method = item.receiving_method
                item.product.forEach(k => {
                    products.push({ 'product_id': k.id, count: k.buyNumber })
                })
            }
        })
        
        // 自提不需要收货
        if (receiving_method == 1) {
            let address_id = this.data.address_id;
            if (!address_id || !this.data.addressInfo) {
                this.setData({
                    payBtn: true
                })
                wx.showToast({
                    title: '请填写地址收货',
                    icon: 'none',
                    duration: 1500
                })
                return false
            }
        }

        if (this.data.currentSelectTime == '') {
            this.setData({
                payBtn: true
            })

            return false
        }

        let addre = this.data.addressInfo ? this.data.addressInfo.id : ''
        new Promise(function (resolve, reject) {
            http.request({
                url: api.orderSubmit,
                method: "POST",
                data: {
                    products,
                    extras: {
                        shop_id: pid,
                        address_id: addre,
                        receiving_method: receiving_method,
                        appointment_time: that.data.currentSelectTime.selecthours,
                        appointment_day: that.data.currentSelectTime.selectdayId,
                        remarks: ''
                    },
                    cookbookids
                },
                success: (res) => {
                    if (res.msg && res.error_code) {
                        wx.showToast({
                            title: res.msg,
                            icon: 'none',
                            duration: 1500
                        });
                        that.setData({
                            payBtn: true
                        })
                        return;
                    }
                    if (res.code == 200) {

                        if (res.data.pass == false && !res.data.order_no) {
                            wx.showToast({
                                title: '下单失败',
                                icon: 'none',
                                duration: 1500
                            });

                            that.setData({
                                payBtn: true
                            })
                            return;
                        }

                        const data = res.data;
                        that.setData({
                            orderDetail: data
                        })
                        resolve(data)

                    }
                    //订单库存检测未通过
                    if (!res.pass) {
                        reject(res)
                    }
                    // 订单检测未通过
                    if (!res.order_id == '-1') {
                        reject(res)
                    }
                },
                fail: (res) => {
                    reject(res)
                }
            })
        }).then((res) => {
            // 调起支付接口
            that.payOrder(res);
        })
    },
    moreComment(e) {
        let id = e.currentTarget.dataset.id;
        wx.navigateTo({
            url: '/pages/comments/comments?id=' + id
        })
    },
    payOrder(result) {
        let that = this
        let order_no = result.order_no;
        return new Promise((resolve, reject) => {
            http.request({
                url: api.preOrder,
                data: {
                    order_no
                },
                success: res => {
                    if (res.msg && res.error_code) {
                        wx.showToast({
                            title: res.msg,
                            icon: 'none',
                            duration: 1500
                        });
                        return;
                    }

                    if (res.code == 200) {
                        let data = res.data
                        // 调起微信支付
                        wx.requestPayment({
                            'timeStamp': data.timeStamp,
                            'nonceStr': data.nonceStr,
                            'package': data.package,
                            'signType': 'MD5',
                            'paySign': data.paySign,
                            'success': function (res) {
                                that.updataPayList();
                                wx.navigateTo({
                                    url: '/pages/payCartSuccess/payCartSuccess'
                                })

                            },
                            'fail': function (res) {
                                wx.navigateTo({
                                    url: '/pages/payCartSuccess/payCartSuccess?order=' + order_no
                                })
                                console.log('支付失败', res);

                            },
                            'complete': function (res) {
                                that.setData({
                                    payBtn: true
                                })
                                wx.setStorageSync("select-menus", '')

                                that.payNotify(order_no)
                            }
                        })

                    }
                },
                fail(res) {

                }


            })
        })
    },
    // 支付接口调用完成之后订单查询
    payNotify() {
        let that = this;
        var orderDetail = this.data.orderDetail
        http.request({
            url: api.payNotify,
            method: "POST",
            data: {
                order_no: orderDetail.order_no
            },
            success: (res) => {
            },
            fail: (res) => {
            }
        })

    },
    updataPayList() {
        var orderDetail = this.data.orderDetail;
        var payList = wx.getStorageSync('payList');
        orderDetail.snap_items.forEach((item) => {
            payList.forEach((k, index) => {
                if (k.product_id == item.id) {
                    payList.splice(index, 1)
                }
            })
        })
        wx.setStorageSync('payList', payList);
    },
    // 选择提货方式
    receiveMethod(e) {
        var pid = e.currentTarget.dataset.pid;
        var shopList = this.data.shopList;
        var receiveType = e.detail.value; //配送方式
        shopList.forEach(item => {
            if (item.id == pid) {
                item.receiving_method = receiveType
            }
        })
        this.setData({
            shopList
        })
    },
    // 关闭
    timeClose() {
        this.setData({
            timerShow: false
        })
    },
    // 选择配送日
    selectDay(e) {
        let timeIndex = e.currentTarget.dataset.index;
        this.setData({
            currentTimeIndex: timeIndex
        })
    },
    selectHour(e) {
        let hourIndex = e.currentTarget.dataset.index;
        let selectTime = this.data.selectTime[this.data.currentTimeIndex];

        let selectDay = selectTime.day;
        let selectHours = selectTime.hours.find((item, index) => {
            return index == hourIndex
        })
        this.setData({
            currentHourIndex: hourIndex,
            timerShow: false,
            currentSelectTime: selectDay + ' ' + selectHours
        })
    },


    // 获得用户的附近服务范围的所有商家列表-菜谱
    choiceMerchantShop(lat, lng, shopId, meunsId) {
        let that = this
        http.request({
            url: api.choiceMerchantShopList,
            method: "POST",
            data: {
                lat: lat,
                lng: lng
            },
            success: (res) => {
                if (res.code == 200) {
                    const data = res.data;
                    data.forEach((ele) => {
                        shopId.push(ele.id)
                    })
                    //附近店铺
                    if (data) {
                        // 如果条件是 满多少送商品，则拿到商品id请求商品名称
                        // 循环请求，顺序拿到，判断添加
                        that.toDistanceFixed(data)
                        data.forEach((ele, index) => {
                            if (ele.yh.length > 0) {
                                ele.yh.forEach((sEle, sIndex) => {
                                    if (sEle.pon) {
                                        if (sEle.pon.type == 2) {
                                            let product_id = Number.parseInt(sEle.discounts)
                                            that.showDetail(product_id).then((product_data) => {
                                                sEle.product_name = product_data.name
                                            })
                                        }
                                    }

                                })
                            }
                        });

                        let promises = data.map((ele, index) => {
                            //可售卖菜谱
                            return that.shopMeunLabel(ele.id, meunsId)
                        })
                        Promise.all(promises).then((allData) => {
                            that.getLabel(allData);
                            //当有店铺，但店铺没有 可售卖的菜谱
                            let shopListDisable = allData.every((ele) => {
                                return ele.length == 0
                            })
                            if (shopListDisable) {
                                this.setData({
                                    shopListDisable: true
                                })
                            }
                            this.setData({
                                label: allData
                            })
                            data.forEach((ele, index) => {
                                allData.forEach((sEle, sIndex) => {
                                    if (index == sIndex) {
                                        ele.label = sEle
                                    }
                                })
                            })
                            that.setData({
                                shopList: data
                            })
                        }).catch((err) => {
                            console.log(err);
                        })

                        // //评***价
                        let promises2 = data.map((ele, index) => {
                            return that.shopTalk(ele.id)
                        })
                        Promise.all(promises2).then((allData) => {
                            data.forEach((ele, index) => {
                                allData.forEach((sEle, sIndex) => {
                                    if (index == sIndex) {
                                        let comment = that.getShopTalk(sEle)
                                        ele.comment = comment
                                    }
                                })
                            })
                            that.setData({
                                shopList: data
                            })
                        }).catch((err) => {
                            console.log(err);
                        })
                    }
                } else if (res.code == 201) {
                    const data2 = res.data;
                    data2.forEach((ele) => {
                        shopId.push(ele.id)
                    })
                    that.setData({
                        disableShopList: data2
                    })
                }
            },
            fail: (res) => {
                console.log('error', res)
            }
        })
    },
    onShow: function () {
        let address = wx.getStorageSync('address');
        this.setData({
            address_id: address.id,
            address: address.title
        })
        http.request({
            url: api.getAddressInfo,
            method: "POST",
            data: {
                community_id: address.id,
            },
            success: (res) => {
                if (res.code == 200) {
                    if (res.data) {
                        let data = res.data
                        this.setData({
                            addressInfo: data
                        })
                    }

                }
            },
            fail: (res) => {
                console.log('error', res)
            }
        })
        this.setData({
            address_id: address.id,
            address: address.address
        })
    },

    foldList(e, myClc, myIndex, myIdx) {
        let menuid = e.currentTarget.dataset.menuid;
        let clc, meunIndex, idx;
        let localItem = this.data.localItem;
        if (myClc == 0) {
            clc = myClc
        } else {
            clc = e.currentTarget.dataset.first; //折叠防止重复请求
        }

        let that = this;
        if (myIndex == 0) {
            meunIndex = myIndex
        } else {
            meunIndex = e.currentTarget.dataset.index; // wxml内 点击菜谱对应的索引值
        }

        let currentProductId = [];
        let mainProductId = []; //主食材id
        let repalceId = []; // 主食材id
        //显示隐藏
        if (myIdx == 0) {
            idx = myIdx
        } else {
            idx = e.currentTarget.dataset.index;
        }
        var memberList = this.data.singleShopMenus;
        for (let i = 0; i < memberList.length; i++) { // 展开收缩判断
            if (idx == i) {
                memberList[i].open = !memberList[i].open;

            }
        };
        this.setData({
            singleShopMenus: memberList
        });

        if (clc == 0) {
            let singleShopMenus = this.data.singleShopMenus
            singleShopMenus[meunIndex].clc = 1
            this.setData({
                singleShopMenus: singleShopMenus
            })
            //依据接口，遍历所有的单品id——循环请求
            let promises = currentProductId.map((i, num) => {
                //可售卖菜谱
                return that.getThreeProducts(i, shopId, menuid)
            })
            Promise.all(promises).then((allData) => {
                allData.forEach((res, num) => {
                    if (res[0].missing && res[0].missing == true) {
                        typeclasses[num].missing = true
                        // repalceId = repalceId.filter((ele) => {
                        //   return ele !== i
                        // })
                    } else {
                        typeclasses[num].missing = false
                    }
                    typeclasses[num].son = res
                    localItem[meunIndex] = typeclasses;
                })

                wx.setStorageSync('localItem', localItem)
                this.setData({
                    myAllItem: localItem,
                })
            }).catch((err) => {
                console.log(err);
            })
            //只遍历 主食材的id， 确定主食材是否确实，以便展示替换的菜谱
            mainProductId.forEach((i, num) => {
                that.getThreeProducts(i, shopId, menuid).then((res) => {
                    //先确定该菜谱是否 缺失主材，只有一个主食材时
                    //这一步是删除 缺失主材的id，保留存在的主材id
                    if (res[0].missing && res[0].missing == true) {
                        repalceId = repalceId.filter((ele) => {
                            return ele !== i
                        })
                        that.replaceCookbooks(repalceId, shopId).then((res) => {
                            let replaceCookbooks = []
                            replaceCookbooks[meunIndex] = res;
                            that.setData({
                                replaceCookbooks: replaceCookbooks
                            })
                        })
                    } else {
                    }
                });
            })


        }

    },


    getLabel(allData) { //店铺可卖菜谱标签
        let ret = []
        let p1 = 0
        let p2 = 0
        // 循环全部-计算预估价
        allData.forEach((ele, index) => {
            if (ele != undefined) {
                ele.forEach((ele) => {
                    p1 += divideByHundred(ele.floorprice)
                    p2 += divideByHundred(ele.topprice)
                })
                ret[index] = {
                    floor: p1.toFixed(0),
                    top: p2.toFixed(0)
                }
            }
        }, 0)
        this.setData({
            priceTotal: ret
        })
    },
    toDistanceFixed(arr) {
        const ret = arr.map((item) => {
            if (item.distance == 0) {
                return 0
            }
            return item.distance.toFixed(2)
        })
        this.setData({
            distance: ret
        })
    },

    // 拿到满送的商品 名称
    showDetail(product_id) {
        return new Promise(function (resolve, reject) {
            http.request({
                url: 'https://api.weigeee.com/api/Product/getOne',
                method: "POST",
                data: {
                    id: product_id,
                },
                success: (res) => {
                    let data = res.data
                    resolve(data)
                },
                fail: (res) => {
                    console.log('error', res)
                }
            })
        })


    },
    //获取店铺可售卖菜谱
    shopMeunLabel(shopId, menusId) {
        let that = this
        let ret = []
        let num = menusId.join(",");
        return new Promise(function (resolve, reject) {
            http.request({
                // url: 'https://api.weigeee.com/api/Cart/shopBooks',
                url: api.shopBookList,
                method: "POST",
                data: {
                    id: shopId, //商户id
                    uoids: num //菜谱id
                },
                success: (res) => {
                    if (res.error_code == 201) {
                        let msg = []
                        resolve(msg)
                    } else if (res.code == 200) {
                        let data = res.data;
                        resolve(data);
                    }
                },
                fail: (res) => {
                    console.log('error', res)
                }
            })
        })
    },
    // 获取 每个店铺的评***价
    shopTalk(id) {
        return new Promise(function (resolve, reject) {
            http.request({
                // url: 'https://api.weigeee.com/api/Status/getAppraises',
                url: api.getAppraisesList,
                method: "POST",
                data: {
                    page: 1,
                    size: 10,
                    id: id //店铺id
                },
                success: (res) => {
                    if (res.code == 200) {
                        let data = res.data;
                        resolve(data);
                    } else if (res.error_code == 201) { //店铺 暂无评***价时
                        let msg = [];
                        resolve(msg)
                    }
                },
                fail: (res) => {
                    console.log('error', res)
                }
            })

        })

    },
    getShopTalk(data) {
        // 一一对应店铺评***价 - 随机取三条 - 评分大于>= 4且有内容，然后拼接，循环滚动
        let comment = []; // 重构的 店铺评***价
        if (data.length = 0) {

        } else {
            for (let i in data) {
                //重构结构，去除评***价数量，好评率字段
                if (data[i] instanceof Object) {
                    comment.push(data[i])
                    // if (data[i].grade >= 4 && data[i].grade < 6) {}
                }
            }
        }
        return comment
    },
    bindMultiPickerChange: function (e) {
        this.setData({
            multiIndex: e.detail.value
        })

        let HandValue = e.detail.value;
        let objectMultiArray = this.data.objectMultiArray;
        let selectname = objectMultiArray[0][HandValue[0]].cnName
        let selectdayId = objectMultiArray[0][HandValue[0]].dayId;
        let selecthours = objectMultiArray[1][HandValue[1]].name;
        this.setData({
            currentSelectTime: {
                selectname,
                selectdayId,
                selecthours
            }
        })

    },
    bindMultiPickerColumnChange: function (e) {
        // 初始化数据
        var data = {
            objectMultiShow: this.data.objectMultiShow,
            multiArray: this.data.multiArray,
            multiIndex: this.data.multiIndex
        };

        // 改变第i列数据之后，后几列选择第0个选项（重置）
        data.multiIndex[e.detail.column] = e.detail.value;
        for (let i = e.detail.column; i < data.multiIndex.length - 1; i++) {
            data.multiIndex[i + 1] = 0
        }
        let arry = this.data.objectMultiArray
        for (let i = e.detail.column; i < data.multiIndex.length - 1; i++) {
            data.objectMultiShow[i + 1] = arry[i + 1].filter(item => item.parentId === data.objectMultiShow[i][data.multiIndex[i]].id)
            data.multiArray[i + 1] = data.objectMultiShow[i + 1].map(item => item.name)
        }
        // 数据更新
        this.setData(data);
    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {
        let selectedMenus = wx.getStorageSync('select-menus')
        if (selectedMenus) {
            selectedMenus.forEach((ele, i) => {
                return ele.greyOff = false
            })
            wx.setStorageSync('select-menus', selectedMenus)
        }

    },


})